const express = require('express');
const axios = require('axios');
const router = express.Router();
const pool = require('../models/database.js');

const APPID = 'wxfc0a7c8a02742860';
const SECRET = '5ccfa5b8cfc395c63036f8b8eea3de73';

router.post('/login', async (req, res) => {
  const { code, avatarUrl, nickName } = req.body;
  if (!code) return res.status(400).json({ code: 400, message: '缺少 code' });


  try {
    const result = await axios.get(
      'https://api.weixin.qq.com/sns/jscode2session',
      {
        params: {
          appid: APPID,
          secret: SECRET,
          js_code: code,
          grant_type: 'authorization_code'
        }
      }
    );

    const { openid } = result.data;
    if (!openid) {
      return res.status(500).json({ code: 500, message: '获取 openid 失败', data: result.data });
    }

    const [users] = await pool.query('SELECT * FROM users WHERE openid = ?', [openid]);
    let user = users[0];

    if (!user) {
      await pool.query(
        'INSERT INTO users (openid, avatarUrl, nickName) VALUES (?, ?, ?)',
        [openid, avatarUrl || '', nickName || '']
      );
      const [newUsers] = await pool.query('SELECT * FROM users WHERE openid = ?', [openid]);
      user = newUsers[0];
    }

    res.json({ code: 200, data: user });
  } catch (err) {
    console.error(err);
    res.status(500).json({ code: 500, message: '请求微信失败或数据库异常' });
  }
});

router.get('/profile', async (req, res) => {
  const { openid } = req.query;
  if (!openid) return res.json({ code: 400, message: '缺少 openid' });
  try {
    const [rows] = await pool.query('SELECT * FROM users WHERE openid = ?', [openid]);
    if (rows.length === 0) return res.json({ code: 404, message: '用户不存在' });

    const user = rows[0];
    try {
      user.pet_preference = JSON.parse(user.pet_preference || '[]');
    } catch (e) {
      user.pet_preference = [];
    }

    res.json({ code: 200, data: user });
  } catch (err) {
    res.json({ code: 500, message: '服务器错误' });
  }
});


router.post('/profile', async (req, res) => {
  const {
    openid, avatarUrl, fullName, phone, address, pet_preference, gender
  } = req.body;

  if (!openid) return res.json({ code: 400, message: '缺少 openid' });

  try {
    const prefStr = JSON.stringify(pet_preference);
    console.log(`更新用户: ${openid}`, { avatarUrl, fullName, phone, address, pet_preference: prefStr });

    await pool.query(
      `UPDATE users SET avatarUrl = ?, fullName = ?, phone = ?, address = ?, pet_preference = ?, gender = ? WHERE openid = ?`,
      [avatarUrl, fullName, phone, address, prefStr, gender, openid]
    );

    res.json({ code: 200, message: '更新成功' });
  } catch (err) {
    console.error('更新失败', err);
    res.json({ code: 500, message: '服务器错误' });
  }
});




module.exports = router;
